package com.example.armmvvm.ui.fallview

import android.view.View
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 *
 * 包名：com.example.armmvvm.ui.fallview
 * 文件描述：
 * 创建人：yanghaozhang
 * 创建时间：2023/1/6 13:37
 * 修改人：
 * 修改时间：
 * 修改备注：
 * @Version:1.0
 */

fun View.postFlow(delayTime: Long = -1): Flow<Unit> {
    return callbackFlow {
        val runnable: Runnable = kotlinx.coroutines.Runnable {
            trySendBlocking(Unit)
                .onFailure { throwable ->
                    throwable?.printStackTrace()
                }
            channel.close()
        }
        if (delayTime < 0) {
            post(runnable)
        } else {
            postDelayed(runnable, delayTime)
        }
        awaitClose { removeCallbacks(runnable) }
    }
}

suspend fun View.awaitPost(delayTime: Long = -1) = suspendCoroutine { coroutine ->
    val runnable = Runnable {
        coroutine.resume(this)
    }
    if (delayTime < 0) {
        post(runnable)
    } else {
        postDelayed(runnable, delayTime)
    }
}